xquery version "0.9-ml"

(: $root is a string representing the root node from which the id will be checked and the node to be updated will be calculted 
$id is the id of the node to update
$node is the node to update from the the end of the provided root
$value is the value the nodes text will updated to

the entire query is put into a string and evaluated because when mixing standard query evaluations with those that had been evaluated from a string, an error was thrown stating that external nodes could not be updated

further, within the string, there is no guarantee that a node will have a value. Text() returns an error when evaluating agains an empty element. So when inserting values we need to construct the lowest level element repersentation of the value e.g. <tag>val</tag>
:)

let $arg_root := xdmp:get-request-field("root")
let $arg_id := xdmp:get-request-field("id")
let $arg_node := xdmp:get-request-field("node")
let $arg_value := xdmp:get-request-field("value")

(:these variables are for testing :)
let $root := "doc('wines.xml')/wines/wine"
let $id := "128"
let $node := "alcohol"
let $value := "4"

let $insertLine := if ($arg_value eq "")
then " let $tempVal := concat($temp2, ' ', $temp3)"
else concat(" let $tempVal := concat($temp2,'", $arg_value, "', $temp3) 

				 ")

let $s := concat("let $root := ",$arg_root, " for $r in $root ",

				 " let $temp := fn:name($r/", $arg_node,") 
				 ",

                 " let $temp2 := concat('<',$temp,'>') 
				 ",

				 " let $temp3 := concat('</',$temp,'>')
				 ",

				 $insertLine,

				 " where $r/@id=",$arg_id, "
				 ",

				 " return 
				 ",

				 " xdmp:node-replace($r/", $arg_node, "
				 ",
				 
				 ", xdmp:eval($tempVal", ") )"
(:				 " xdmp:node-replace($r/", $node, ", <blendPercentage>", $value, "</blendPercentage>)" :)
(:				 " xdmp:node-replace($r/",$node,"/text(), xdmp:unquote('",$value,"')/text())" :)
				  )
return
xdmp:eval($s),
<result>true</result>







